package com.linzp.bishe.common;

import com.google.code.kaptcha.Producer;
import com.linzp.bishe.utils.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName CaptchaController
 * @Description 验证码操作处理
 * @Author LinZePeng
 * @Date 2021/11/18 15:22
 * @Version 1.0
 */
@RestController
public class CaptchaController {

	@Resource(name = "captchaProducerMath")
	private Producer captchaProducerMath;

	@Autowired
	private RedisCache redisCache;

	/**
	 * 生成验证码
	 */
	@GetMapping("/captchaImage")
	public Result getCode(HttpServletResponse response) throws IOException {
		Result ajax = Result.success();

		// 保存验证码信息
		String uuid = UUID.randomUUID().toString();
		String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;

		String capStr = null, code = null;
		BufferedImage image = null;

		// 生成验证码
		String capText = captchaProducerMath.createText();
		capStr = capText.substring(0, capText.lastIndexOf("@"));
		code = capText.substring(capText.lastIndexOf("@") + 1);
		image = captchaProducerMath.createImage(capStr);

		redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
		// 转换流信息写出
		FastByteArrayOutputStream os = new FastByteArrayOutputStream();
		try {
			ImageIO.write(image, "jpg", os);
		} catch (IOException e) {
			return Result.error(e.getMessage());
		}

		ajax.put("uuid", uuid);
		//用base64帮忙传输图片
		ajax.put("img", Base64.encode(os.toByteArray()));
		return ajax;
	}
}
